﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WITM.DAL
{
    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private readonly DAL.WhereIsTheMoneyDBEntities context;
        private IUserRepository userRepository;
        private ISpendingCategoryRepository spendingCategoryRepository;
        private ISpendingItemRepository spendingItemRepository;
        private ISpendingEntryRepository spendingEntryRepository;

        public UnitOfWork(WhereIsTheMoneyDBEntities context)
        {
            this.context = context;
            userRepository = new UserRepository(context);
            spendingCategoryRepository = new SpendingCategoryRepository(context);
            spendingItemRepository = new SpendingItemRepository(context);
            spendingEntryRepository = new SpendingEntryRepository(context);
        }

        public UnitOfWork(IUserRepository userRepository, 
            ISpendingCategoryRepository spendingCategoryRepository,
            ISpendingItemRepository spendingItemRepository)
        {
            this.userRepository = userRepository;
            this.spendingCategoryRepository = spendingCategoryRepository;
            this.spendingItemRepository = spendingItemRepository;
        }

        public IUserRepository UserRepository
        {
            get { return userRepository; }
        }

        public ISpendingCategoryRepository SpendingCategoryRepository
        {
            get { return spendingCategoryRepository; }
        }

        public ISpendingItemRepository SpendingItemRepository
        {
            get { return spendingItemRepository; }
        }

        public ISpendingEntryRepository SpendingEntryRepository
        {
            get { return spendingEntryRepository; }
        }

        #region IUnitOfWork Members

        public void Commit()
        {
            context.SaveChanges();
        }

        #endregion

        #region IDisposable Members

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
